﻿package com.sohu.sns.avatar {
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.system.Capabilities;
	
	public class CameraSnapper extends Sprite implements IEditSource {
		private var os : String;
		private var camera : Camera;
		private var bitmapData : BitmapData;
		private var video : Video;
		public static var NOCAMERA : String = "nocamera";
		public static const MAC_CAM : String = "USB Video Class Video";

		public function CameraSnapper() {
		}

		public function getEditSource() : void {
			if (this.camera) {
				this.bitmapData = new BitmapData(this.video.width, this.video.height);
				this.bitmapData.draw(this.video, null, null, null, null, true);
			}
		}

		private function connectCamera() : void {
			this.camera.setMode(640, 480, 21);
			this.camera.setQuality(0, 100);
			this.video.attachCamera(this.camera);
		}

		public function init() : void {
			this.os = Capabilities.manufacturer;
			this.video = new Video();
			addChild(this.video);
			this.initCamera();
		}

		public function get editData() : BitmapData {
			return this.bitmapData;
		}

		private function initCamera() : void {
			if (this.os == "Adobe Macintosh") {
				for (var key : String in Camera.names) {
					if (Camera.names[key] == MAC_CAM) {
						var name : String = key.toString();
						break;
					}
				}
				this.camera = Camera.getCamera(name);
			} else {
				this.camera = Camera.getCamera();
			}
			if (this.camera != null && Camera.names.length >= 1) {
				this.connectCamera();
			} else {
				this.dispatchEvent(new Event(NOCAMERA));
			}
		}

		public function IEditSource() : * {
		}
	}
}
